package cn.sfa.controller.manage;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.taglib.CommonCache;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.DateUtil;
import cn.sfa.common.utils.MajorKeyGenerate;
import cn.sfa.common.utils.TableNameEnum;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.affixItem.SaleAffixItem;
import cn.sfa.entity.manage.FastProductInfo;
import cn.sfa.entity.manage.SaleProduct;
import cn.sfa.entity.system.BranchSysCode;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.affix.AffixService;
import cn.sfa.service.product.ProductService;

@Controller
@RequestMapping("/productandtrain/product/index")
public class ManageProductController extends WebInitBinderContoller {

	Logger log = Logger.getLogger(ManageProductController.class);

	@Autowired
	ProductService productService;

	@Autowired
	AffixService affixService;
	@Autowired
	MajorKeyGenerate majorKeyGenerate;

	/*
	 * 查询产品
	 */
	@RequestMapping()
	public String index(
			@RequestParam(value = "productCode", required = false) String productCode, // 获得产品代码
			@RequestParam(value = "productname", required = false) String productTitle, // 获得产品名称
			@RequestParam(value = "provides", required = false) String productSupplier, // 获得供应商
			@RequestParam(value = "datebegin", required = false) String datebegin, // 获得起售日期始
			@RequestParam(value = "dateend", required = false) String dateend, // 获得起售日期止
			@RequestParam(value = "branchId", required = false) String branchId, // 获得机构
			@RequestParam(value = "stopdatebegin", required = false) String stopdatebegin, // 获得停售日期始
			@RequestParam(value = "stopdateend", required = false) String stopdateend, // 获得停售日期止
			@RequestParam(value = "releasetatus", required = false) String releasetatus, // 获得状态
			@RequestParam(value = "currentPage", required = false) String currentPage,// 页码
			@RequestParam(value = "channeltype", required = false) String channeltype,// 销售渠道
			@RequestParam(value = "salestatus", required = false) String salestatus,// 销售状态
			HttpServletRequest request, HttpServletResponse response,
			ModelMap map) throws UnsupportedEncodingException {
		System.out.println("-------------------------------------------");
		System.out.println(releasetatus);
		String providername = "";
		String providerStr = "";
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		if(productSupplier != null){	 
		providername = productSupplier.substring(productSupplier.indexOf(":")+1,productSupplier.length());	 
		providerStr = providername ;
		if(providername.lastIndexOf("(") > -1){
			providerStr = providername.substring(0,providername.lastIndexOf("("));
			 
			}
		} 
		String currentBranchId = user.getBranchId();
		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}
		String url = request.getContextPath()
				+ "/productandtrain/product/index?"
				+ "providerStr="
				+ CommonUtil.jugeAndFixNull(providerStr)
				+ "&productCode="
				+ CommonUtil.jugeAndFixNull(productCode)
				+ "&productTitle="
				+ CommonUtil.jugeAndFixNull(productTitle)
				+ "&channeltype="
				+ CommonUtil.jugeAndFixNull(channeltype)
				+ "&salestatus="
				+ CommonUtil.jugeAndFixNull(salestatus)
				+ "&datebegin="
				+ (CommonUtil.isEmpty(datebegin) ? "" : DateUtil
						.stringToDate(datebegin))
				+ "&dateend="
				+ (CommonUtil.isEmpty(dateend) ? "" : DateUtil
						.stringToDate(dateend))
				+ "&branchId="
				+ CommonUtil.jugeAndFixNull(branchId)
				+ "&stopdatebegin="
				+ (CommonUtil.isEmpty(stopdatebegin) ? "" : DateUtil
						.stringToDate(stopdatebegin))
				+ "&stopdateend="
				+ (CommonUtil.isEmpty(stopdateend) ? "" : DateUtil
						.stringToDate(stopdateend)) + "&releasetatus="
				+ CommonUtil.jugeAndFixNull(releasetatus);

		Pagination pagination = productService.SeachProduct(pageIndex, 10, url,
				branchId, productCode, productTitle, providerStr,
				datebegin, dateend, stopdatebegin, stopdateend, releasetatus,
				currentBranchId, channeltype, salestatus);

		map.put("productCode", productCode);
		map.put("productTitle", productTitle);
		map.put("providerStr", providerStr);
		map.put("datebegin", datebegin);
		map.put("channeltype", channeltype);
		map.put("salestatus", salestatus);
		map.put("dateend", dateend);
		map.put("branchId", branchId);
		map.put("stopdatebegin", stopdatebegin);
		map.put("stopdateend", stopdateend);
		map.put("productSupplier", productSupplier);

		map.put("releasetatus", releasetatus);
		map.put("pagination", pagination);
		List<BranchSysCode> list = null;

		map.put("BranchList", list);

		return "/manage/product/index";
	}

	/*
	 * 显示产品信息
	 */
	@RequestMapping("/publish/{productId}")
	public String publish(@PathVariable("productId") String productId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap map) {

		FastProductInfo productInfo = productService
				.getFastProductByID(productId);
		SaleProduct saleproduct = productService
		.getSaleProductByproductId(productId);

		// 查询这个产品是否已经发布过了
		boolean isPublished = productService.getIsPublished(productId);

		// 如果已经发布,那么就把附件列表查出来
		if (isPublished) {
			List<SaleAffixItem> affixList = affixService.getAffix(
					"SALEPRODUCT", productId);
			map.put("affixList", affixList);
		}
		List<SaleAffixItem> affixList1 = productService.getAffix("SALEPRODUCT1",productId);
		List<SaleAffixItem> affixList2 = productService.getAffix("SALEPRODUCT2",productId);
		List<SaleAffixItem> affixList3 = productService.getAffix("SALEPRODUCT3",productId);
		List<SaleAffixItem> affixList4 = productService.getAffix("SALEPRODUCT4",productId);
		List<SaleAffixItem> affixList5 = productService.getAffix("SALEPRODUCT2",productId);
		List<SaleAffixItem> affixList6 = productService.getAffix("SALEPRODUCT6",productId);
		List<SaleAffixItem> affixList7 = productService.getAffix("SALEPRODUCT7",productId);
		List<SaleAffixItem> affixList8 = productService.getAffix("SALEPRODUCT8",productId);
		List<SaleAffixItem> affixList9 = productService.getAffixForPlanBook("SALEPROVIDERPLANBOOK",productId);
		
		map.put("affixList1", affixList1);
		map.put("affixList2", affixList2);
		map.put("affixList3", affixList3);
		map.put("affixList4", affixList4);
		map.put("affixList5", affixList5);
		map.put("affixList6", affixList6);
		map.put("affixList7", affixList7);
		map.put("affixList8", affixList8);
		map.put("affixList9", affixList9);
		map.put("saleproduct", saleproduct);
		map.put("productInfo", productInfo);
		map.put("isPublished", isPublished);

		return "/manage/product/publish";
	}

	/*
	 * Ajax发布
	 */
	@ResponseBody
	@RequestMapping("/ajaxPublish")
	public String ajaxPublish(
			@RequestParam(value = "affixmainid", required = false) String productId, // 产品ID
			@RequestParam(value = "affixStr1", required = false) String affixStr1,  
			@RequestParam(value = "affixStr2", required = false) String affixStr2,  
			@RequestParam(value = "affixStr3", required = false) String affixStr3,   
			@RequestParam(value = "affixStr4", required = false) String affixStr4,  
			@RequestParam(value = "affixStr5", required = false) String affixStr5,  
			@RequestParam(value = "affixStr6", required = false) String affixStr6,  
			@RequestParam(value = "affixStr7", required = false) String affixStr7, 
			@RequestParam(value = "affixStr8", required = false) String affixStr8,
			@RequestParam(value = "otherInfo", required = false) String otherInfo, // 附件列表
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setContentType("text/html");

		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");

		SaleProduct model = new SaleProduct();
		model.setSaleproductid(majorKeyGenerate
				.keyGenerate(TableNameEnum.SALEPRODUCT));// 主键ID
		model.setCreateDate(new Date());// 创建日期
		model.setCreateUser(user.getSaleUsersLoginId());// 创建用户

		FastProductInfo productInfo = productService
				.getFastProductByID(productId);
		model.setProductid(productId);// Fast产品Id
		model.setProductcode(productInfo.getProductcode());// 产品编码
		model.setProductname(productInfo.getProductname());// 产品名称
		model.setIsAffix("N");
		model.setSalestatus(productInfo.getSalestatus());// 销售状态
		model.setOtherinfo(otherInfo);
		model.setSalestatus("SALESTATUS_S2");
		String message = "";
		// 发布
		try {
			if (!CommonUtil.isEmpty(affixStr1)) {
				affixService.saveAffix(affixStr1, "SALEPRODUCT1", model
						.getProductid());
				model.setIsAffix("Y");
				}
				if (!CommonUtil.isEmpty(affixStr2)) {
					affixService.saveAffix(affixStr2, "SALEPRODUCT2", model
							.getProductid());
					model.setIsAffix("Y");
					}
				if (!CommonUtil.isEmpty(affixStr3)) {
					affixService.saveAffix(affixStr3, "SALEPRODUCT3", model
							.getProductid());
					model.setIsAffix("Y");
				}
				if (!CommonUtil.isEmpty(affixStr4)) {
					affixService.saveAffix(affixStr4, "SALEPRODUCT4", model
							.getProductid());
					model.setIsAffix("Y");
				}
				if (!CommonUtil.isEmpty(affixStr5)) {
					affixService.saveAffix(affixStr5, "SALEPRODUCT5", model
							.getProductid());
					model.setIsAffix("Y");
				}
				if (!CommonUtil.isEmpty(affixStr6)) {
					affixService.saveAffix(affixStr6, "SALEPRODUCT6", model
							.getProductid());
					model.setIsAffix("Y");
				}
				if (!CommonUtil.isEmpty(affixStr7)) {
					affixService.saveAffix(affixStr7, "SALEPRODUCT7", model
							.getProductid());
					model.setIsAffix("Y");
				}
				if (!CommonUtil.isEmpty(affixStr8)) {
					affixService.saveAffix(affixStr8, "SALEPRODUCT8", model
							.getProductid());
					model.setIsAffix("Y");
				}
			productService.insertSaleProduct(model);
			message = "{result:true}";
		} catch (Exception ex) {
			message = "{result:false,message:'发布失败!错误信息:" + ex.getMessage()
					+ "'}";
		}
		return message;
	}

	/**
	 * Ajax修改
	 */
	@RequestMapping("/ajaxEdit")
	public @ResponseBody
	String ajaxEdit(
			@RequestParam(value = "affixmainid", required = false) String productId, // 产品ID
			@RequestParam(value = "affixStr1", required = false) String affixStr1,  
			@RequestParam(value = "affixStr2", required = false) String affixStr2,  
			@RequestParam(value = "affixStr3", required = false) String affixStr3,   
			@RequestParam(value = "affixStr4", required = false) String affixStr4,  
			@RequestParam(value = "affixStr5", required = false) String affixStr5,  
			@RequestParam(value = "affixStr6", required = false) String affixStr6,  
			@RequestParam(value = "affixStr7", required = false) String affixStr7, 
			@RequestParam(value = "affixStr8", required = false) String affixStr8,
			@RequestParam(value = "otherInfo", required = false) String otherInfo,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setContentType("text/html");
		String message = "";
		
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");

		SaleProduct model = productService.getSaleProductByproductId(productId);
		model.setUpdateDate(new Date());// 修改日期
		model.setUpdateUser(user.getSaleUsersLoginId());// 修改用户
		model.setOtherinfo(otherInfo);
		model.setIsAffix("N");
		model.setSalestatus("SALESTATUS_S2");
		
		try {
			// 保存附件
			
			if (!CommonUtil.isEmpty(affixStr1)) {
			affixService.saveAffix(affixStr1, "SALEPRODUCT1", model
					.getProductid());
			model.setIsAffix("Y");
			}
			if (!CommonUtil.isEmpty(affixStr2)) {
				affixService.saveAffix(affixStr2, "SALEPRODUCT2", model
						.getProductid());
				model.setIsAffix("Y");
				}
			if (!CommonUtil.isEmpty(affixStr3)) {
				affixService.saveAffix(affixStr3, "SALEPRODUCT3", model
						.getProductid());
				model.setIsAffix("Y");
			}
			if (!CommonUtil.isEmpty(affixStr4)) {
				affixService.saveAffix(affixStr4, "SALEPRODUCT4", model
						.getProductid());
				model.setIsAffix("Y");
			}
			if (!CommonUtil.isEmpty(affixStr5)) {
				affixService.saveAffix(affixStr5, "SALEPRODUCT5", model
						.getProductid());
				model.setIsAffix("Y");
			}
			if (!CommonUtil.isEmpty(affixStr6)) {
				affixService.saveAffix(affixStr6, "SALEPRODUCT6", model
						.getProductid());
				model.setIsAffix("Y");
			}
			if (!CommonUtil.isEmpty(affixStr7)) {
				affixService.saveAffix(affixStr7, "SALEPRODUCT7", model
						.getProductid());
				model.setIsAffix("Y");
			}
			if (!CommonUtil.isEmpty(affixStr8)) {
				affixService.saveAffix(affixStr8, "SALEPRODUCT8", model
						.getProductid());
				model.setIsAffix("Y");
			}
			productService.updateSaleProduct(model);	
			message = "{result:true}";
			
		} catch (Exception ex) {
			message = "{result:false,message:'修改失败!错误信息:" + ex.getMessage()
					+ "'}";
		}
	
		return message;
	}

	/**
	 * 产品详细信息
	 */
	@RequestMapping("/info/{productId}")
	public String productInfo(@PathVariable("productId") String productId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap map) {
		List<SaleAffixItem> affixList1 = productService.getAffix("SALEPRODUCT1",productId);
		List<SaleAffixItem> affixList2 = productService.getAffix("SALEPRODUCT2",productId);
		List<SaleAffixItem> affixList3 = productService.getAffix("SALEPRODUCT3",productId);
		List<SaleAffixItem> affixList4 = productService.getAffix("SALEPRODUCT4",productId);
		List<SaleAffixItem> affixList5 = productService.getAffix("SALEPRODUCT2",productId);
		List<SaleAffixItem> affixList6 = productService.getAffix("SALEPRODUCT6",productId);
		List<SaleAffixItem> affixList7 = productService.getAffix("SALEPRODUCT7",productId);
		List<SaleAffixItem> affixList8 = productService.getAffix("SALEPRODUCT8",productId);
		List<SaleAffixItem> affixList9 = productService.getAffixForPlanBook("SALEPROVIDERPLANBOOK",productId);
		
		map.put("affixList1", affixList1);
		map.put("affixList2", affixList2);
		map.put("affixList3", affixList3);
		map.put("affixList4", affixList4);
		map.put("affixList5", affixList5);
		map.put("affixList6", affixList6);
		map.put("affixList7", affixList7);
		map.put("affixList8", affixList8);
		map.put("affixList9", affixList9);
		FastProductInfo productInfo = productService
				.getFastProductByID(productId);

		SaleProduct saleproduct = productService
				.getSaleProductByproductId(productId);

		// 查询这个产品是否已经发布过了
		boolean isPublished = productService.getIsPublished(productId);

		map.put("isPublished", isPublished);
		map.put("saleproduct", saleproduct);
		map.put("productInfo", productInfo);
		return "/manage/product/productinfo";
	}

	/*
	 * 产品关联
	 */
	@RequestMapping("salepro")
	public String saleProduct(
			@RequestParam(value = "productCode", required = false) String productCode,
			@RequestParam(value = "productTitle", required = false) String productTitle,
			@RequestParam(value = "productProvider", required = false) String productProvider,
			@RequestParam(value = "currentPage", required = false) String currentPage,// 页码
			HttpServletRequest request, ModelMap map,
			HttpServletResponse response) {

		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		String currentBranchId = user.getBranchId();
		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}
		String url = request.getContextPath()
				+ "/productandtrain/product/index/salepro?" + "productCode="
				+ CommonUtil.jugeAndFixNull(productCode) + "&productTitle="
				+ CommonUtil.jugeAndFixNull(productTitle) + "&productProvider="
				+ CommonUtil.jugeAndFixNull(productProvider);

		Pagination pagination = productService.RelevanceSaleProduct(pageIndex,
				10, url, productCode, productTitle, productProvider,
				currentBranchId);

		map.put("productCode", productCode);
		map.put("productTitle", productTitle);
		map.put("productProvider", productProvider);
		map.put("pagination", pagination);
		return "/manage/product/saleproduct";
	}
	
	/**
	 * 计划书 产品关联
	 * TODO
	 * @author: LiXiang
	 * @param productCode
	 * @param productTitle
	 * @param productProvider
	 * @param currentPage
	 * @param request
	 * @param map
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("saleplanbook")
	public String saleProductForPlan(
			@RequestParam(value = "productCode", required = false) String productCode,
			@RequestParam(value = "productTitle", required = false) String productTitle,
			@RequestParam(value = "productProvider", required = false) String productProvider,
			@RequestParam(value = "currentPage", required = false) String currentPage,// 页码
			HttpServletRequest request, ModelMap map,
			HttpServletResponse response) throws UnsupportedEncodingException {
		request.setCharacterEncoding("utf-8");
		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");
		String currentBranchId = user.getBranchId();
		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}
		String url = request.getContextPath()
				+ "/productandtrain/product/index/saleplanbook?" + "productCode="
				+ CommonUtil.jugeAndFixNull(productCode) + "&productTitle="
				+ CommonUtil.jugeAndFixNull(productTitle) + "&productProvider="
				+ CommonUtil.jugeAndFixNull(productProvider);

		Pagination pagination = productService.RelevanceSaleProduct(pageIndex,
				10, url, productCode, productTitle, productProvider,
				currentBranchId);

		map.put("productCode", productCode);
		map.put("productTitle", productTitle);
		map.put("productProvider", productProvider);
		map.put("pagination", pagination);
		return "/manage/product/saleplanbook";
	}

	@SuppressWarnings("unused")
	@RequestMapping("/stopnotice/{productId}")
	private void stopnotice(@PathVariable("productId") String productId,
			HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String result;
		try {
			result = productService.stopNotice(productId) ? "true" : "false";
		} catch (Exception ex) {
			log.info("==============" + ex.getMessage());
			result = "false";
		}
		out.print(result);
		out.flush();
		out.close();
	}
}
